<?php
namespace Base\Cache;

use Zend\Cache\Storage\Adapter\FilesystemOptions;
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;

class FileCache extends \Zend\Cache\Storage\Adapter\Filesystem{

    protected  $sm = null;

    public function __construct($sm)
    {
        $this->sm = $sm;
        $fileCacheConfig = $sm->get('config')['file-cache-config'];
        $this->fileOption = $fileOptions = new FilesystemOptions($fileCacheConfig);

        parent::__construct($fileOptions);
    }


    public function setFileItem($key, $value, $ttl = 0)
    {
        if($key == 'key-ttl')
            throw new \Exception('key Illegal');

        $this->handleTtl($key, $ttl);
        $this->getOptions()->setTtl($ttl);
        $value = serialize($value);
        return $this->setItem($key, $value); // TODO: Change the autogenerated stub
    }

    public function getFileItem($key, & $success = null, & $casToken = null)
    {
        $ttl = $this->getHandleTtl($key);
        $this->getOptions()->setTtl($ttl);

        $val =  $this->getItem($key, $success, $casToken); // TODO: Change the autogenerated stub
        return unserialize($val);
    }


    public function handleTtl($key, $ttl){
        $kTtls = unserialize($this->getItem('key-ttl'));
        $kTtls[$key] = $ttl;
        $this->setItem('key-ttl', serialize($kTtls));
    }

    public function getHandleTtl($key){
        $keyObj = new self($this->sm);
        $ttls = unserialize($keyObj->getItem('key-ttl'));
        return  $ttls[$key];
    }

}